package com.user.util;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.user.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @program: Member_Perks_Store
 * @description:
 * @author: 无恙
 * @create: 2024-06-18 11:59
 **/


@Slf4j
@Component
public class RequestUtil {
    private static final String UNKNOWN = "unknown";
    private static final String EMPTY_IP = "";
    private static IRedisService staticRedisService;

    private IRedisService redisService;

    @Autowired
    public void setRedisService(IRedisService redisService) {
        this.redisService = redisService;
    }

    @PostConstruct
    public void init() {
        RequestUtil.staticRedisService = this.redisService;
    }

    /**
     * 获取当前网络ip
     * @return IP地址
     */
    public static String getIp(){
        return getIp(RequestHolder.getHttpServletRequest());
    }
    /**
     * 获取当前网络ip
     * @return IP地址
     */
    public static List<String> getIps(){
        return getIps(RequestHolder.getHttpServletRequest());
    }

    /**
     * 获取当前网络ip
     * @param request HTTP请求
     * @return IP地址
     */
    public static String getIp(HttpServletRequest request){
        List<String> ips = getIps(request);
        if(!ips.isEmpty()){
            return ips.get(0);
        }
        return EMPTY_IP;
    }
    /**
     * 获取当前网络ip
     * @param request HTTP请求
     * @return IP地址，如果使用了代理则返回多个IP地址，并以","分隔，第一个为原始IP
     */
    public static List<String> getIps(HttpServletRequest request){
        List<String> ips = new ArrayList<>(2);
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")){
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();

                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(StringUtils.isNotBlank(ip)){
            String[] strs = ip.split(",");
            for (String str : strs) {
                if(StringUtils.isNotBlank(str)){
                    ips.add(str.trim());
                }
            }
        }
        return ips;
    }

    /**
     * 获取当前机器的IP:用于服务器监控
     *
     * @return 本机IP
     */
    public static String getLocalIp() {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
                NetworkInterface anInterface = interfaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) {
                    InetAddress inetAddr = inetAddresses.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr.getHostAddress();
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress.getHostAddress();
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                return "";
            }
            return jdkSuppliedAddress.getHostAddress();
        } catch (Exception e) {
            return "";
        }
    }


    /**
     * 获取浏览器信息
     * @param request HTTP 请求对象
     * @return 返回浏览器名称：如Chrome
     */
    public static String getBrowser(HttpServletRequest request) {
        return UserAgentUtil.parse(request.getHeader("User-Agent")).getBrowser().toString();
    }
    /**
     * 获取OS信息
     * @param request HTTP 请求对象
     * @return 返回操作系统名称：如Windows
     */
    public static String getOS(HttpServletRequest request) {
        return UserAgentUtil.parse(request.getHeader("User-Agent")).getOsVersion();
    }
    /**
     * 获取User-Agent解析信息
     * @param request HTTP 请求对象
     * @return 返回UserAgent对象：可以获取对象中的各种数据
     */
    public static UserAgent getUserAgent(HttpServletRequest request) {
        return UserAgentUtil.parse(request.getHeader("User-Agent"));
    }

    public static SysUser getUser(){
        return (SysUser) StpUtil.getSession().get("LOGIN_USER");
    }

    public static Long getUserId(){
        return StpUtil.isLogin()?StpUtil.getLoginIdAsLong():null;
    }
    public static String getUserName(){
        return StpUtil.isLogin()?getUser().getUsername():null;
    }
}
